// src/main/java/org/example/backend/service/UserService.java
package org.example.backend.service;

import org.example.backend.dto.UserManagementDto;
import org.example.backend.dto.UserProfileDto;
import org.example.backend.dto.UserQueryDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.UserRepository;
import org.example.backend.repository.StudentRepository;
import org.example.backend.repository.TeacherRepository;
import org.example.backend.repository.CompanyRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

@Service
@Transactional
public class UserService {

    private final UserRepository userRepository;
    private final StudentRepository studentRepository;
    private final TeacherRepository teacherRepository;
    private final CompanyRepository companyRepository;
    private final PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository,
                       StudentRepository studentRepository,
                       TeacherRepository teacherRepository,
                       CompanyRepository companyRepository,
                       PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.studentRepository = studentRepository;
        this.teacherRepository = teacherRepository;
        this.companyRepository = companyRepository;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 创建用户
     */
    public User createUser(UserManagementDto userDto) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(userDto.getUsername()).isPresent()) {
            throw new BusinessException("用户名已存在");
        }

        User user = new User();
        user.setUsername(userDto.getUsername());
        // 设置默认密码为123456
        user.setPassword(passwordEncoder.encode("123456"));
        user.setEmail(userDto.getEmail());
        user.setPhone(userDto.getPhone());
        user.setRole(userDto.getRole());
        user.setStatus(userDto.getStatus());

        return userRepository.save(user);
    }

    /**
     * 更新用户
     */
    public User updateUser(Long userId, UserManagementDto userDto) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 检查用户名是否已被其他用户使用
        if (userRepository.existsByUsernameAndIdNot(userDto.getUsername(), userId)) {
            throw new BusinessException("用户名已存在");
        }

        user.setUsername(userDto.getUsername());
        user.setEmail(userDto.getEmail());
        user.setPhone(userDto.getPhone());
        user.setRole(userDto.getRole());
        user.setStatus(userDto.getStatus());

        return userRepository.save(user);
    }

    /**
     * 删除用户（软删除）
     */
    public void deleteUser(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 不能删除自己
        if (user.getRole() == User.Role.ADMIN) {
            throw new BusinessException("不能删除管理员账户");
        }

        user.setStatus(0); // 软删除，设置状态为inactive
        userRepository.save(user);
    }

    /**
     * 获取用户详情
     */
    @Transactional(readOnly = true)
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
    }

    /**
     * 分页查询用户
     */
    @Transactional(readOnly = true)
    public PageResponseDto<UserManagementDto> getUsers(UserQueryDto queryDto,Pageable pageable) {
//        Pageable pageable = PageRequest.of(queryDto.getPage(), queryDto.getSize(),
//                                          Sort.by(Sort.Direction.DESC, "createdAt"));

        User.Role role = null;
        if (queryDto.getRole() != null && !queryDto.getRole().isEmpty()) {
            try {
                role = User.Role.valueOf(queryDto.getRole().toUpperCase());
            } catch (IllegalArgumentException e) {
                throw new BusinessException("无效的角色类型");
            }
        }

        Page<User> userPage = userRepository.findByConditions(
                queryDto.getUsername(),
                role,
                queryDto.getStatus(),
                pageable
        );

        return new PageResponseDto<>(
                userPage.getContent().stream()
                        .map(this::convertToDto)
                        .collect(Collectors.toList()),
                userPage.getTotalElements(),
                userPage.getTotalPages(),
                queryDto.getPage(),
                queryDto.getSize()
        );
    }

    /**
     * 重置用户密码
     */
    public void resetPassword(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 重置为默认密码123456
        user.setPassword(passwordEncoder.encode("123456"));
        userRepository.save(user);
    }

    /**
     * 启用/禁用用户
     */
    public void toggleUserStatus(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 不能禁用自己
        if (user.getRole() == User.Role.ADMIN) {
            throw new BusinessException("不能禁用管理员账户");
        }

        // 切换状态：0->1, 非0->0
        user.setStatus(user.getStatus() == 0 ? 1 : 0);
        userRepository.save(user);
    }

    /**
     * 将User实体转换为UserManagementDto
     */
    private UserManagementDto convertToDto(User user) {
        UserManagementDto dto = new UserManagementDto();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setPhone(user.getPhone());
        dto.setRole(user.getRole());
        dto.setStatus(user.getStatus());

        // 根据用户角色获取真实姓名或企业名称
        switch (user.getRole()) {
            case STUDENT:
                studentRepository.findByUserId(user.getId()).ifPresent(student ->
                    dto.setRealName(student.getName())
                );
                break;
            case TEACHER:
                teacherRepository.findByUserId(user.getId()).ifPresent(teacher ->
                    dto.setRealName(teacher.getName())
                );
                break;
            case COMPANY:
                companyRepository.findByUserId(user.getId()).ifPresent(company ->
                    dto.setRealName(company.getName())
                );
                break;
            case ADMIN:
                dto.setRealName("管理员");
                break;
        }

        return dto;
    }

    /**
     * 根据用户名获取用户
     */
    @Transactional(readOnly = true)
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
    }

    /**
     * 更新用户个人信息
     */
    public User updateUserProfile(Long userId, UserProfileDto profileDto) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        user.setEmail(profileDto.getEmail());
        user.setPhone(profileDto.getPhone());

        return userRepository.save(user);
    }

    /**
     * 获取用户个人信息
     */
    @Transactional(readOnly = true)
    public User getUserProfile(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
    }

    /**
     * 直接更新用户信息（绕过角色检查）
     */
    public User updateUserDirectly(User user) {
        return userRepository.save(user);
    }


}
